package tech.aistar.day11;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 本类用来演示: 线程的通信
 * 俩个线程
 *
 * 12A34B56C
 *
 * @author: success
 * @date: 2022/8/2 9:57 上午
 */
public class LockConditionDemo {
    private Lock lock = new ReentrantLock();

    //唤醒指定的线程
    //有几个线程任务,创建几个队列
    private Condition c1 = lock.newCondition();//数字
    private Condition c2 = lock.newCondition();//字母

    //定义一个标记位
    private boolean flag;//false

    public void printNum(){
        try {
            lock.lock();
            for (int i = 1; i <=52; i+=2) {
                if(flag){
                    try {
                        c1.await(); // 等待阻塞,需要其他线程环境
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.print(i);
                System.out.print(i+1);
                flag = true;
                c2.signal();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printLetter(){
        //alt+ctrl+t => try...catch..finally块
        try {
            lock.lock();
            for (char i = 'A'; i <='Z' ; i++) {
                if(!flag){
                    //等待阻塞
                    try {
                        c2.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.print(i);
                flag = false;
                //唤醒c1
                c1.signal();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
class LockConditionDemoTest{
    public static void main(String[] args) {
        LockConditionDemo conditionDemo = new LockConditionDemo();
        Thread t1 = new Thread(()->conditionDemo.printLetter());
        Thread t2 = new Thread(()->conditionDemo.printNum());
        t1.start();
        t2.start();
    }
}
